<template>
  <view class="readtime__chart">
    <view class="readtime__chart-desc">
      <view class="readtime__chart-item" v-for="item in datas" :key="item.name">
        <text class="readtime__chart-box" />
        <text class="readtime__chart-name">{{ item.name }}</text>
      </view>
    </view>
  </view>
</template>

<script>
const colors = ['#1CD5C9', '#74EDE5', '#B0FFFA', '#DBFFFD'];

export default {
  props: {
    total: Number,
    datas: Array,
  },

  watch: {
    total() {
      this.$nextTick(() => {
        this.drawChart();
      });
    },
  },

  onLoad() {
    this.$nextTick(() => {
      this.drawChart();
    });
  },

  methods: {
    drawChart() {
      // 根据后台获取到的数据计算比例
      const sum = +this.total || 100; // 总计
      const ctx = uni.createCanvasContext('circle-canvas'); // 拿到canvas对象（自己的定义的canvas-id）
      // 开始绘制第一条路径 总数 红色
      ctx.beginPath(); // 开始绘制路径
      ctx.arc(57, 57, 41, 0, 2 * Math.PI); // arc画圆
      ctx.setStrokeStyle('#f2f2f2'); // 线条颜色
      ctx.setLineWidth(16); // 线条宽度
      ctx.stroke(); // 绘制成线条（fill()是填充为饼图）

      // 绘制环形
      let startPos = 1.5 * Math.PI;
      this.datas.forEach((item, index) => {
        const value = parseFloat((item.num / sum).toFixed(2)); // 实际
        // 开始绘制第二条路径 成交 橘色
        ctx.beginPath();
        ctx.arc(57, 57, 41, startPos, value * Math.PI);
        ctx.setStrokeStyle(colors[index]);
        ctx.setLineWidth(16);
        ctx.stroke();
        startPos += value * Math.PI;
      });

      // 填充字体-367
      ctx.setFillStyle('#2B3133');
      ctx.setFontSize(14);
      ctx.setTextAlign('center');
      ctx.fillText(`${this.total}本`, 57, 62);
      ctx.stroke();
      // 渲染
      ctx.draw();
    },

    getColor(index) {
      return colors[index] || '#999';
    },
  },
};
</script>

<style lang="scss" scoped>
.readtime__chart {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: flex-start;

  &-box {
    display: inline-block;
    width: 20rpx;
    height: 20rpx;
    margin-right: 16rpx;
  }

  &-box:first-child {
    background: #1cd5c9;
  }

  &-box:nth-child(2) {
    background: #74ede5;
  }

  &-box:nth-child(3) {
    background: #b0fffa;
  }

  &-box:nth-child(4) {
    background: #dbfffd;
  }

  &-name {
    font-size: 26rpx;
    color: #95a1a6;
    line-height: 60rpx;
  }
}

.canvas {
  width: 228rpx;
  height: 228rpx;
  margin-right: 120rpx;
}
</style>
